var lang;
var ds_id;
var ds_type;
var idStr;
var relation_id;

String.prototype.trim=function(){
	return this.replace(/^\s*|\s*$/g, "");
};
$(document).ready(function(){
	lang = $("#lang").val();
	ds_id = $("#ds_id").val();
	ds_type = $("#ds_type").val();
	idStr = $("#idStr").val();
	relation_id = $("#relation_id").val();//==0
	var ok_btn;
	var cancel_btn;
	if(lang == 'en'){
		ok_btn = "OK";
		cancel_btn = "Cancel";
	}else if(lang == 'zh'){
		ok_btn = "确定";
		cancel_btn = "取消";
	}
//	if (relation_id != "0") {
//	initialize(relation_id, ds_type, ds_id);
//} else {
	initializeNew();
//}
	var classSelectionDiv = createClassSelectionDiv(ds_id, ds_type, idStr);
	classSelectionDiv.addClass("showing");
	$(".tabs").after(classSelectionDiv);
	
	$("#classTab").live("click",function(){
		var panel = $("#class_select");
		if($(panel).hasClass("showing")){
			return;
		}else{
			var oldTab = $(".active");
			oldTab.removeClass("active")
			$(this).parent().addClass("active");
			
			var old = $(".showing");
			$(old).removeClass("showing");
			$(old).hide();
			$(panel).addClass("showing");
			$(panel).show();
		}
	});
	$("#propertyTab").live("click",function(){
		var panel = $("#property_select");
		if($(panel).length>0){
			if($(panel).hasClass("showing")){
				return;
			}
		}else{
			panel = createPropertySelectionDiv(ds_id, ds_type, idStr);
			$(".tabs").after(panel);
		}
		var oldTab = $(".active");
		oldTab.removeClass("active");
		$(this).parent().addClass("active");
		
		var old = $(".showing");
		$(old).removeClass("showing");
		$(old).hide();
		$(panel).addClass("showing");
		$(panel).show();	
	});
	$("#cancel_btn").live("click", function(){
//		window.close();
		if(ds_id>0){
			var location = "/sview/dataset/"+ds_type.charAt(0)+ds_id;
			if(lang=="zh"){
				location += "&lang=zh";
			}
			window.location=location;
		}else{
			var location = "/sview/dataset/"+ds_type.charAt(0)+idStr;
			if(lang=="zh"){
				location += "&lang=zh";
			}
			window.location=location;
		}
	});
	$("#ok_btn").live("click",function(){
		var pli = $("input[name=radioSelector]:checked").parent();
		if(pli==undefined || $(pli).length==0){
			if(lang == 'en'){
				alert("Please select a class or a property as start, or click cancel to leave.");
			}else if(lang == 'zh'){
				alert("请选择一个类作为起始点，或点击取消");
			}
		}else{
			var data = {};
			var s = pli.attr("s");
			var p = pli.attr("p");
			var o = pli.attr("o");
			data["s"] = s;
			data["p"] = p;
			data["o"] = o;
			data["id"] = relation_id+"";
			data["ds_type"] = ds_type;
			data["ds_id"] = ds_id;
			data["idStr"] = idStr;
			data = JSON.stringify(data);
			data = ("data="+encodeURIComponent(data));
			$.ajax({
				url: "/sview/expandAdd",
				async: true,
				data: data,
				dataType: 'json',
				type: 'post',
				success: function(result){
					if(result["err"] == "err"){
						if(lang == 'en'){
							alert("Failed, please try latter.");
						}else if(lang == 'zh'){
							alert("操作失败，请稍后再试");
						}
					}else{
						var url = "relation_edit.jsp?relation_id="+relation_id
							+"&ds_type="+ds_type
							+"&ds_id="+ds_id
							+"&idStr="+idStr
							+"&lang="+lang;
						window.location = url;
					}
				}
			});
		}
	});
	/*$("#start_class").live("click",function(){
		var classSelectionDiv = createClassSelectionDiv(ds_id, ds_type);
		var num = $(classSelectionDiv).attr("num");
		var h = (num * 25)+100;
		$(classSelectionDiv).dialog({
			modal: true,
			minWidth: 450,
			height: h,
			top: 150,
			buttons:[{
				text: ok_btn,
				click: function(){
					var cid = $("input[name=classRadio]:checked").val();
					if(cid==undefined){
						if(lang == 'en'){
							alert("Please select a class as start, or click cancel.");
						}else if(lang == 'zh'){
							alert("请选择一个类作为起始点，或点击取消");
						}
					}else{
						var data = {};
						data["s"] = "v1";
						data["p"] = "478384";//==================rdf:type
						data["o"] = cid;
						data["id"] = relation_id+"";
						data["ds_type"] = ds_type;
						data["ds_id"] = ds_id;
						data = JSON.stringify(data);
						data = ("data="+encodeURIComponent(data));
						$.ajax({
							url: "/sview/expandAdd",
							async: true,
							data: data,
							dataType: 'json',
							type: 'post',
							success: function(result){
								if(result["err"] == "err"){
									if(lang == 'en'){
										alert("Failed, please try latter.");
									}else if(lang == 'zh'){
										alert("操作失败，请稍后再试");
									}
								}else{
									var url = "relation_edit.jsp?relation_id="+relation_id
										+"&ds_type="+ds_type
										+"&ds_id="+ds_id
										+"&lang="+lang;
									window.location = url;
								}
							}
						});
					}
				}
			},{
				text: cancel_btn,
				click: function(){
					$(classSelectionDiv).dialog("close");
				}
			}]
		});//end of dialog
	});
	$("#start_property").live("click",function(){
		var propertySelectionDiv = createPropertySelectionDiv(ds_id, ds_type);//createClassSelectionDiv(ds_id, ds_type);
		var num = $(propertySelectionDiv).attr("num");
		var h = (num * 25)+100;
		$(propertySelectionDiv).dialog({
			modal: true,
			minWidth: 450,
			height: h,
			top: 150,
			buttons:[{
				text: ok_btn,
				click: function(){
					var pli = $("input[name=propertyRadio]:checked").parent();
					if(pli==undefined){
						if(lang == 'en'){
							alert("Please select a class as start, or click cancel.");
						}else if(lang == 'zh'){
							alert("请选择一个类作为起始点，或点击取消");
						}
					}else{
						var data = {};
						var s = pli.attr("s");
						var p = pli.attr("p");
						var o = pli.attr("o");
						data["s"] = s;
						data["p"] = p;
						data["o"] = o;
						data["id"] = relation_id+"";
						data["ds_type"] = ds_type;
						data["ds_id"] = ds_id;
						data = JSON.stringify(data);
						data = ("data="+encodeURIComponent(data));
						$.ajax({
							url: "/sview/expandAdd",
							async: true,
							data: data,
							dataType: 'json',
							type: 'post',
							success: function(result){
								if(result["err"] == "err"){
									if(lang == 'en'){
										alert("Failed, please try latter.");
									}else if(lang == 'zh'){
										alert("操作失败，请稍后再试");
									}
								}else{
									var url = "relation_edit.jsp?relation_id="+relation_id
										+"&ds_type="+ds_type
										+"&ds_id="+ds_id
										+"&lang="+lang;
									window.location = url;
								}
							}
						});
					}
				}
			},{
				text: cancel_btn,
				click: function(){
					$(propertySelectionDiv).dialog("close");
				}
			}]
		});//end of dialog
	});*/
	
});
function initializeNew() {
	var data = {};
	data["id"] = "0";
//	data["gid"] = $("#gid").val();
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationIntoSession",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#expand").show();
		}
	});
}

function createClassSelectionDiv(ds_id, ds_type, idStr){
	$("#class_select").remove();
	var div = $("<div id='class_select' class='selectDialog panel span'></div>");
	if(lang=="en"){
		div.attr("title","Class Selection");
	}else if(lang=="zh"){
		div.attr("title","选择类");
	}
	$(div).attr("num",0);
	var ul = $("<ul id='class_select_ul'></ul>");
	div.append(ul);
	var data = {};
	data["ds_id"] = ds_id+"";
	data["ds_type"] = ds_type;
	data["idStr"] = idStr;
	data = JSON.stringify(data);
	data = ("getclasses="+encodeURIComponent(data));
	
	$.ajax({
		url: "/sview/relationExpandFromNew",
		async: false,
		data: data,
		dataType: 'xml',
		type: 'post',
		success: function(doc){
			$(doc).find("class").each(function(){
				var id = $(this).children("id").text();
				var name = $(this).children("name").text();
				var uri = $(this).children("uri").text();
				var li = $("<li></li>");
//				$(li).attr("id", id);
//				$(li).attr("uri", uri);
				li.attr("s", "v1");
				li.attr("p", "478384");//==================
				li.attr("o", "u"+id);
				
				$(ul).append(li);
//				var radio = $("<input type='radio' name='classRadio'/>");
				var radio = $("<input type='radio' name='radioSelector'/>");
				$(radio).attr("value", "u"+id);
//				alert($(radio).val());
				$(li).append(radio);
				var span = $("<span></span>");
				$(span).text(name);
				$(li).append(span);
				var num =  parseInt($(div).attr("num"));
				num = num+1;
				$(div).attr("num",num);
				var childrenUl = addChildren($(this),div);
				$(li).append(childrenUl);
			});
			if($(doc).find("class").length == 0){//no result returned
				var lang = $("#lang").val();
				var li = $("<li></li>");
				var span = $("<span class='info'></span>");
				if(lang == "en"){
					span.text("No rdf:type statement in current dataset。");
				}else{
					span.text("当前数据集中未声明rdf:type。");
				}
			}
		}//end of success
	});//end of ajax
	return div;
}
function createPropertySelectionDiv(ds_id, ds_type, idStr){
	$("#property_select").remove();
	var div = $("<div id='property_select' class='selectDialog panel span'></div>");
	if(lang=="en"){
		div.attr("title","Property Selection");
	}else if(lang=="zh"){
		div.attr("title","选择类");
	}
	$(div).attr("num",0);
	var ul = $("<ul id='property_select_ul'></ul>");
	div.append(ul);
	var data = {};
	data["ds_id"] = ds_id+"";
	data["ds_type"] = ds_type;
	data["idStr"] = idStr;
	data = JSON.stringify(data);
	data = ("getproperties="+encodeURIComponent(data));
	
	$.ajax({
		url: "/sview/relationExpandFromNew",
		async: false,
		data: data,
		dataType: 'json',
		type: 'post',
		success: function(result) {
			$("#onloading").dialog("close");
			var array = result["result"];
			$(ul).html("");
			for ( var i = 0; i < array.length; i++) {
				var triple = array[i];
				var stext = new String(triple["stext"]);
				var ptext = new String(triple["ptext"]);
				var otext = new String(triple["otext"]);
				var s = new String(triple["s"]);
				var p = triple["p"];
				var o = new String(triple["o"]);
				var s_dis = stext;
				var p_dis = ptext;
				var o_dis = otext;
				if (s.indexOf("u") == 0) {
					s_dis = getLocalname(stext);
				}
				p_dis = getLocalname(ptext);
				if (o.indexOf("u") == 0) {
					o_dis = getLocalname(otext);
				}
				var li = $("<li></li>");
				li.attr("s", s);
				li.attr("p", p);
				li.attr("o", o);
//				var radio = $("<input type='radio' name='propertyRadio'/>");
				var radio = $("<input type='radio' name='radioSelector'/>");
				$(li).append(radio);
				var span = $("<span></span>");
//				$(span).html("(<span title='" + stext + "'>" + s_dis
//						+ "</span>,<span title='" + ptext + "'>"
//						+ p_dis + "</span>,<span title='" + otext
//						+ "'>" + o_dis + "</span>)");
				$(span).html("<span title='" + ptext + "'>"
						+ p_dis + "</span>");
				$(li).append(span);
				$(ul).append(li);
				var num =  parseInt($(div).attr("num"));
				num = num+1;
				$(div).attr("num",num);
			}
			if(i==0){//no result returned
				
			}
		}//end of success
	});//end of ajax
	return div;
}
function addChildren(parent,div){
	var content = $("<ul></ul>");
	$(parent).children("subclass").each(function(){
		var id = $(this).children("id").text();
		var name = $(this).children("name").text();
		var uri = $(this).children("uri").text();
		var li = $("<li></li>");
//		$(li).attr("id", id);
//		$(li).attr("uri", uri);
		li.attr("s", "v1");
		li.attr("p", "478384");//==================
		li.attr("o", "u"+id);
		
		$(content).append(li);
		var radio = $("<input type='radio' name='radioSelector'/>");
		$(radio).attr("value", id);
		$(li).append(radio);
		var span = $("<span></span>");
		$(span).text(name);
		$(li).append(span);
		var num = parseInt($(div).attr("num"));
		num = num+1;
		$(div).attr("num",num);
		var childrenUl = addChildren($(this));
	});//end of each
	return content;
}